<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品分类名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品分类名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品分类" prop="categoryPath">
        <el-cascader
          v-model="queryParams.categoryPath"
          :options="categoryOptions"
          :props="{
            children: 'children',
            label: 'name',
            value: 'id',
            checkStrictly: true
          }"
          placeholder="请选择商品分类"
          clearable
          style="width: 300px"
          @change="handleCategoryChange"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAddFirstLevel"
          v-hasPermi="['lkshop:good_class:add']"
        >添加一级分类</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Refresh"
          @click="handleRefresh"
        >刷新列表</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 树形表格 -->
    <el-table
      v-loading="loading"
      :data="goodClassList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="分类名称" prop="name" min-width="200">
        <template #default="scope">
          <span :style="{ paddingLeft: (scope.row.level - 1) * 20 + 'px' }">
            {{ scope.row.name }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="分类等级" align="center" prop="level" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.level === 1" type="primary">一级分类</el-tag>
          <el-tag v-else-if="scope.row.level === 2" type="success">二级分类</el-tag>
          <el-tag v-else-if="scope.row.level === 3" type="success">三级分类</el-tag>
          <el-tag v-else type="warning">四级分类</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="goodsType" width="120">
        <template #default="scope">
          <el-tag v-if="scope.row.goodsType === 1" type="info">实物商品</el-tag>
          <el-tag v-else-if="scope.row.goodsType === 2" type="warning">虚拟商品</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="分类图片" align="center" prop="img" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.img" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['lkshop:good_class:edit']">编辑</el-button>
          <el-button 
            v-if="scope.row.level <= 3" 
            link 
            type="success" 
            icon="Plus" 
            @click="handleAddSubCategory(scope.row)" 
            v-hasPermi="['lkshop:good_class:add']"
          >添加子分类</el-button>
          <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['lkshop:good_class:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品分类对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="goodClassRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="父分类" prop="parentId" v-if="form.level !== 1">
          <el-tree-select
            v-model="form.parentId"
            :data="parentOptions"
            :props="{ children: 'children', label: 'name', value: 'id' }"
            placeholder="请选择父分类"
            clearable
            check-strictly
            style="width: 100%"
            @change="handleParentChange"
          />
        </el-form-item>
        <el-form-item label="分类等级" prop="level">
          <el-input v-model="form.level" placeholder="请输入分类等级" />
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsType" v-if="form.level === 1">
          <el-select v-model="form.goodsType" placeholder="请选择商品类型" style="width: 100%">
            <el-option label="实物商品" :value="1" />
            <el-option label="虚拟商品" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品类型" prop="goodsType" v-else>
          <el-input v-model="goodsTypeText" disabled placeholder="继承父分类类型" />
        </el-form-item>
        <el-form-item label="分类图片" prop="img">
          <image-upload v-model="form.img"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Good_class">
import { listGood_class, getGood_class, delGood_class, addGood_class, updateGood_class, getGood_classTree } from "@/api/lkshop/good_class"

const { proxy } = getCurrentInstance()

const goodClassList = ref([])
const parentOptions = ref([])
const categoryOptions = ref([])
const open = ref(false)
const loading = ref(true)
const showSearch = ref(true)
const title = ref("")

const data = reactive({
  form: {},
  queryParams: {
    name: null,
    parentId: null,
    categoryPath: null,
    img: null
  },
  rules: {
    name: [
      { required: true, message: "分类名称不能为空", trigger: "blur" }
    ],
    level: [
      { required: true, message: "分类等级不能为空", trigger: "blur" }
    ],
    goodsType: [
      { required: true, message: "商品类型不能为空", trigger: "blur" }
    ]
  }
})

const { queryParams, form, rules } = toRefs(data)

// 商品类型文本显示
const goodsTypeText = computed(() => {
  if (form.value.goodsType === 1) {
    return '实物商品'
  } else if (form.value.goodsType === 2) {
    return '虚拟商品'
  }
  return '未设置'
})

/** 查询商品分类层级列表 */
function getList() {
  loading.value = true
  
  // 构建查询参数
  const params = {}
  if (queryParams.value.name) {
    params.name = queryParams.value.name
  }
  if (queryParams.value.parentId) {
    params.parentId = queryParams.value.parentId
  }
  
  // 统一使用getGood_classTree，后端会根据参数自动判断是搜索还是普通查询
  getGood_classTree(params).then(response => {
    console.log('API响应:', response)
    goodClassList.value = response.data || []
    loading.value = false
  }).catch(error => {
    console.error('获取分类列表失败:', error)
    goodClassList.value = []
    loading.value = false
  })
}



/** 获取父分类选项 */
function getParentOptions() {
  getGood_classTree({}).then(response => {
    // 获取完整的树形结构作为父分类选项
    parentOptions.value = response.data || []
  })
}

/** 获取分类选项用于搜索 */
function getCategoryOptions() {
  getGood_classTree({}).then(response => {
    // 获取完整的树形结构作为分类选项
    categoryOptions.value = response.data || []
  })
}

/** 处理分类选择变化 */
function handleCategoryChange(value) {
  if (value && value.length > 0) {
    // 获取选中的分类ID（取最后一个，即最具体的分类）
    const selectedCategoryId = value[value.length - 1]
    queryParams.value.parentId = selectedCategoryId
    console.log('选中分类ID:', selectedCategoryId, '完整路径:', value)
  } else {
    queryParams.value.parentId = null
    console.log('清空分类选择')
  }
  // 立即执行搜索
  handleQuery()
}

/** 处理父分类变化 */
function handleParentChange(parentId) {
  if (parentId && form.value.level !== 1) {
    // 根据父分类ID查找对应的分类信息
    const findParentCategory = (categories, targetId) => {
      for (const category of categories) {
        if (category.id === targetId) {
          return category
        }
        if (category.children && category.children.length > 0) {
          const found = findParentCategory(category.children, targetId)
          if (found) return found
        }
      }
      return null
    }
    
    const parentCategory = findParentCategory(parentOptions.value, parentId)
    if (parentCategory) {
      // 继承父分类的商品类型
      form.value.goodsType = parentCategory.goodsType
    }
  }
}

// 取消按钮
function cancel() {
  open.value = false
  reset()
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    parentId: null,
    level: null,
    goodsType: null,
    img: null
  }
  proxy.resetForm("goodClassRef")
}

/** 搜索按钮操作 */
function handleQuery() {
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  // 重置查询参数
  queryParams.value.name = null
  queryParams.value.categoryPath = null
  queryParams.value.parentId = null
  handleQuery()
}

/** 刷新列表 */
function handleRefresh() {
  getList()
}

/** 新增一级分类 */
function handleAddFirstLevel() {
  reset()
  form.value.level = 1
  form.value.parentId = null
  // 获取父分类选项用于选择
  getParentOptions()
  open.value = true
  title.value = "添加一级分类"
}

/** 新增子分类 */
function handleAddSubCategory(row) {
  reset()
  form.value.level = row.level + 1
  form.value.parentId = row.id
  // 继承父分类的商品类型
  form.value.goodsType = row.goodsType
  // 获取父分类选项用于选择
  getParentOptions()
  open.value = true
  title.value = "添加子分类"
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset()
  const _id = row.id
  getGood_class(_id).then(response => {
    form.value = response.data
    // 获取父分类选项用于选择
    getParentOptions()
    open.value = true
    title.value = "修改分类"
  })
}

/** 提交按钮 */
function submitForm() {
  // 动态验证商品类型
  const validateGoodsType = (rule, value, callback) => {
    if (form.value.level === 1 && !value) {
      callback(new Error('一级分类必须选择商品类型'))
    } else {
      callback()
    }
  }
  
  // 临时添加验证规则
  const tempRules = {
    ...rules.value,
    goodsType: [
      { validator: validateGoodsType, trigger: "blur" }
    ]
  }
  
  proxy.$refs["goodClassRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateGood_class(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          open.value = false
          getList()
        })
      } else {
        addGood_class(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          open.value = false
          getList()
        })
      }
    }
  })
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _id = row.id
  proxy.$modal.confirm('是否确认删除分类"' + row.name + '"？').then(function() {
    return delGood_class(_id)
  }).then(() => {
    getList()
    proxy.$modal.msgSuccess("删除成功")
  }).catch(() => {})
}

getList()
getParentOptions()
getCategoryOptions()
</script>

